package spynx.desl.parser.ui.popup.actions;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import spynx.desl.DeslProgram;

public class RunDeslProgram implements IObjectActionDelegate {

	private Shell shell;
	private ISelection selection;
	private IFile selectedFile;
	
	/**
	 * Constructor for Action1.
	 */
	public RunDeslProgram() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		ResourceSet rs;
		rs = new ResourceSetImpl();
		
		System.setProperty("user.dir", new File(selectedFile.getRawLocation().toOSString()).getParent());
		
		Resource resource = rs.getResource(URI.createFileURI(selectedFile.getLocation().toString()), true);
		
		EObject eobj = resource.getContents().get(0);
		EList<Diagnostic> errors = resource.getErrors();
		
		if (errors.size() > 0) {
			for(Diagnostic err: errors) 
				System.out.printf("Error: %s", err.getMessage());
		}
		else {
			DeslProgram prog = (DeslProgram) eobj;
			prog.run(null);
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		this.selectedFile = null;
		if (selection instanceof TreeSelection) {
			Object element = ((TreeSelection) selection).getFirstElement();
			if (element instanceof IFile)
				this.selectedFile = (IFile)element;
		}
		action.setEnabled(selectedFile != null && "desl".equals(selectedFile.getFileExtension()));
	}

}
